package 二叉树.cn.mjj;


import java.util.LinkedList;
import java.util.Queue;

/**
 * 翻转二叉树
 * https://leetcode-cn.com/problems/invert-binary-tree/submissions/
 * @author Mxb
 * @version 1.0
 * @date 2020/5/11 11:11
 */
public class _226_翻转二叉树 {
    public TreeNode invertTree(TreeNode root) {
        // 前序遍历实现
        if (root == null) return null;
        // 交换节点的左右
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
    public TreeNode invertTree3(TreeNode root) {
        // 中序遍历实现
        if (root == null) return null;
        invertTree(root.left);
        // 交换节点的左右
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        return root;
    }

    public TreeNode invertTree1(TreeNode root) {
        // 层序遍历实现
        if (root == null) return null;
        // 初始化一个链表
        Queue<TreeNode> quene = new LinkedList<>();
        //入队
        quene.offer(root);
        // 只要队列不为空，一直循环
        while (!quene.isEmpty()) {
            // 出队
            TreeNode node = quene.poll();
            //交换
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;

            // 查看左右子树
            if (node.left != null) {
                quene.offer(node.left);
            }
            if (node.right != null) {
                quene.offer(node.right);
            }
        }
        return root;
    }
}
